package com.hhhn.wk.login;

import android.content.Context;
import android.content.Intent;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.entity.User;
import com.hhhn.wk.login.perfect.PerfectActivity;
import com.hhhn.wk.main.tab4.pwd.UpPwdActivity;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.AppValidationMgr;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.MD5Util;
import com.hhhn.wk.utils.SharePreferencesUser;
import com.hhhn.wk.utils.mi.AES;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/2/15 0015    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 登录页面
 * * * * * * * * * * * */
public class LoginActivity extends BaseActivity {
    private EditText et_phone;//账号
    private EditText et_pwd;//密码
    private LinearLayout ll_login;//登录
    private TextView up_pwd;//忘记密码
    private TextView tv_goRegister;//注册
    private Context context;
    private BaseActivity activity;
    private LinearLayout activity_login;
    private ImageView iv_visual;//可视密码  m默认 不可见
    private boolean visual=true;
    private User user=null;
    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_login);
        context=LoginActivity.this;
        activity=this;
    }
    @Override
    protected void initView() {
        iv_visual=findViewById(R.id.iv_visual);
        activity_login=findViewById(R.id.activity_login);
        up_pwd=findViewById(R.id.up_pwd);
        tv_goRegister=findViewById(R.id.tv_goRegister);
        et_phone=findViewById(R.id.et_phone);
        et_pwd=findViewById(R.id.et_pwd);
        ll_login=findViewById(R.id.ll_login);
    }
    @Override
    protected void initData() {

    }
    @Override
    protected void initClick() {
        iv_visual.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (visual){
                    iv_visual.setImageResource(R.mipmap.ic_yanjing_p);
                    et_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    visual=false;
                }else {
                    iv_visual.setImageResource(R.mipmap.ic_yanjing_n);
                    et_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    visual=true;
                }
            }
        });
        ll_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                judge();
            }
        });
        //忘记密码
        up_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(context,UpPwdActivity.class);
                intent.putExtra("type",0);
                startActivity(intent);
            }
        });
        //注册
        tv_goRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(context,RegisterActivity.class));
                finish();
            }
        });
    }
    //判断
    private void  judge(){
        String str_phone = et_phone.getText().toString().trim();
        String str_pwd = et_pwd.getText().toString().trim();
        if (str_phone==null||"".equals(str_phone)){
            toastWk("请输入手机号");
            return;
        }
        if (str_pwd==null||"".equals(str_pwd)){
            toastWk("密码不能为空");
            return;
        }
        if (!AppValidationMgr.isPhone(str_phone)){
            toastWk("手机号输入有误，请重新输入");
        }
        /**
         * 吊起后台接口
         */
        getJSON();
    }
    //登录
    public void getJSON() {
        showLoad();
        RequestParams params = AllPublic.getParamsAccount(activity, "/login", false);
        try {
            JSONObject person=new JSONObject();
            person.put("phone",et_phone.getText().toString());
            person.put("password",MD5Util.md5(et_pwd.getText().toString().trim()));
            AES aes = AllPublic.jsonDesPackaging(person);
            params.addParameter("data",aes.getData());
            params.addParameter("key",aes.getKey());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("登录", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String decode) {
                String result = AllPublic.jsonDesDecode(decode);
                Log.d("@", "onSuccess: "+result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {

                        JSONObject data = jsonObject.getJSONObject("data");
                        int isAudit = data.has("isAudit") ? data.getInt("isAudit") : 0;
                        if (isAudit==101301){//审核通过
                            user=new User();
                            toastWk("登录成功");
                            String uid = data.has("id") ? data.getString("id") : "";
                            String Phone = data.has("phone") ? data.getString("phone") : "";
                            String head_portrait = data.has("headProtrait") ? data.getString("headProtrait") : "";
                            String company_address = data.has("companyAddress") ? data.getString("companyAddress") : "";
                            String company_name = data.has("companyName") ? data.getString("companyName") : "";
                            String nickName = data.has("nickName") ? data.getString("nickName") : "";
                            String salt = data.has("salt") ? data.getString("salt") : "";
                            double balance = data.has("balance") ? data.getDouble("balance") : 0;
                            String paymentPassword = data.has("paymentPassword") ? data.getString("paymentPassword") : "";
                            //当用户使用自有账号登录时，可以这样统计：
                            MobclickAgent.onProfileSignIn(Phone);
                            user.setRrb(balance);
                            user.setSalt(salt);
                            user.setUid(uid);
                            user.setUserImg(head_portrait);
                            user.setUserPhone(Phone);
                            user.setUserNickname(nickName);
                            user.setCompany_name(company_name);
                            user.setCompany_address(company_address);
                            user.setIsLogin(2);
//                        //存储
                            SharePreferencesUser.putBean(activity,Constants.USER, user);
                            Log.d("USer", "onSuccess: "+user.toString());
                            sendBR();
                            sendBR2();
                            finish();
                        }else if (isAudit==101303){//未审核
                            String uid = data.has("id") ? data.getString("id") : "";
                            toastWk("先完善资料");
                            Intent intent=new Intent(context,PerfectActivity.class);
                            intent.putExtra("userId",uid);
                            startActivity(intent);
                            finish();
                        }else if (isAudit==101304){//审核中
                            toastWk("审核中");
                            Intent intent=new Intent(context,CheckActivity.class);
                            startActivity(intent);
                            finish();
                        }else {
                            String uid = data.has("id") ? data.getString("id") : "";
                            toastWk("先完善资料");
                            Intent intent=new Intent(context,PerfectActivity.class);
                            intent.putExtra("userId",uid);
                            startActivity(intent);
                            finish();
                        }
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("登录-第二个", ex + "");
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("登录-第三个", cex + "");
                dismissLoad();
            }
            @Override
            public void onFinished() {
                Log.d("登录-第四个", "onFinished");
                dismissLoad();
            }
        });
    }
    public void sendBR(){
        LogWk("登录成功发送广播");
        Intent intent = new Intent();
        intent.setAction(Constants.MBroadcastReceiver);
        sendBroadcast(intent);
    }
    public void sendBR2(){
        activity. LogWk("购物车成功发送广播");
        Intent intent = new Intent();
        intent.setAction(Constants.MBroadcastReceiverCart);
        activity. sendBroadcast(intent);
    }
}
